<template>
    <div>

        <AddChanceDialog ref="AddChanceDialogRef"
                         :options="options" :close="closeAddChance" :visible="dialogAddChanceFormVisible"
                         :callback="addChanceCallBack"></AddChanceDialog>

        <EditChanceDialog
            :options="options" ref="EditChanceDialogRef" :close="closeEditChance" :visible="dialogEditChanceFormVisible"
            :callback="editChanceCallBack"></EditChanceDialog>

        <TrackDialog :options="options" ref="TrackDialogRef" :close="closeTrackDialog"
                     :visible="dialogTrackVisible"></TrackDialog>

        <Bread title="Chance / Chance Management "/>
        <el-row :gutter="30">
            <el-col :span="18">
                <el-card class="box-card-search">
                    <div slot="header" class="clearfix">
                        <span class="title">Search</span>

                    </div>
                    <el-form ref="elForm" :model="searchChanceForm" size="mini"
                             label-position="left">
                        <el-row type="flex" gutter="20" justify="start" align="top">
                            <el-col>

                                <el-form-item label-width="100px" label="chanceName:" prop="chanceName">
                                    <el-input v-model="searchChanceForm.chanceName" placeholder="Please Enter" clearable
                                    >
                                    </el-input>
                                </el-form-item>
                            </el-col>
                            <el-col>

                                <el-form-item label-width="100px" label="chanceCode:" prop="chanceCode">
                                    <el-input v-model="searchChanceForm.chanceCode" placeholder="Please Enter" clearable
                                              style="{width: 100%;margin-left: 10px}">
                                    </el-input>
                                </el-form-item>
                            </el-col>
                            <el-col>

                                <el-form-item label-width="50px" label="time" prop="chanceTime">
                                    <el-date-picker type="daterange" v-model="searchChanceForm.chanceTime"
                                                    format="yyyy-MM-dd"
                                                    value-format="yyyy-MM-dd" style="{width: 100%}"
                                                    start-placeholder="Y-M-D"
                                                    end-placeholder="Y-M-D" range-separator="To"
                                                    clearable></el-date-picker>
                                </el-form-item>
                            </el-col>
                        </el-row>
                        <el-row type="flex" justify="start" align="top">
                            <el-col>

                                <el-form-item label="mgrDept" label-width="86px" prop="customerDept:">
                                    <el-select v-model="searchChanceForm.customerDept" placeholder="Please Enter"
                                               filterable
                                               clearable
                                               style="{width: 100%}">
                                        <el-option v-for="(item, index) in options.customerMgrDeptOptions" :key="index"
                                                   :label="item.label"
                                                   :value="item.value" :disabled="item.disabled"></el-option>
                                    </el-select>
                                </el-form-item>
                            </el-col>
                            <el-col>

                                <el-form-item label="mgrName" label-width="90px" prop="customerMgr">
                                    <el-select v-model="searchChanceForm.customerMgr" placeholder="Please Choose"
                                               filterable
                                               clearable
                                               style="{width: 100%}">
                                        <el-option v-for="(item, index) in options.customerMgrNameOptionsStr"
                                                   :key="index"
                                                   :label="item.label"
                                                   :value="item.value" :disabled="item.disabled"></el-option>
                                    </el-select>
                                </el-form-item>
                            </el-col>
                            <el-col>

                                <el-form-item label-width="60px" label="belong" prop="chanceBelong">
                                    <el-select v-model="searchChanceForm.chanceBelong" placeholder="Please Enter"
                                               filterable
                                               clearable
                                               style="{width: 100%}">
                                        <el-option v-for="(item, index) in options.chanceBelongOptions" :key="index"
                                                   :label="item.label"
                                                   :value="item.value" :disabled="item.disabled"></el-option>
                                    </el-select>
                                </el-form-item>
                            </el-col>
                            <el-col>

                                <el-form-item label-width="60px" label="status" prop="chanceStatus">
                                    <el-select v-model="searchChanceForm.chanceStatus" placeholder="Please Enter"
                                               filterable
                                               clearable
                                               style="{width: 100%}">
                                        <el-option v-for="(item, index) in options.chanceStatusOptions" :key="index"
                                                   :label="item.label"
                                                   :value="item.value" :disabled="item.disabled"></el-option>
                                    </el-select>
                                </el-form-item>
                            </el-col>
                        </el-row>
                        <el-row type="flex" justify="start" align="top">
                            <el-col>

                                <el-form-item label-width="60px" label="phase" prop="chancePhase">
                                    <el-select v-model="searchChanceForm.chancePhase" placeholder="Please Enter"
                                               filterable
                                               clearable
                                               style="{width: 100%}">
                                        <el-option v-for="(item, index) in options.chancePhaseOptions" :key="index"
                                                   :label="item.label"
                                                   :value="item.value" :disabled="item.disabled"></el-option>
                                    </el-select>
                                </el-form-item>
                            </el-col>
                            <el-col>

                                <el-form-item label-width="60px" label="type" prop="chanceType">
                                    <el-select v-model="searchChanceForm.chanceType" placeholder="Please Enter"
                                               filterable
                                               clearable
                                               style="{width: 100%}">
                                        <el-option v-for="(item, index) in options.chanceTypeOptions" :key="index"
                                                   :label="item.label"
                                                   :value="item.value" :disabled="item.disabled"></el-option>
                                    </el-select>
                                </el-form-item>
                            </el-col>
                            <el-col>

                                <el-form-item label-width="60px" label="product" prop="chanceProduct">
                                    <el-select v-model="searchChanceForm.chanceProduct" placeholder="Please Enter"
                                               filterable clearable
                                               style="{width: 100%}">
                                        <el-option v-for="(item, index) in options.productTypeOptions" :key="index"
                                                   :label="item.label"
                                                   :value="item.value" :disabled="item.disabled"></el-option>
                                    </el-select>
                                </el-form-item>
                            </el-col>
                            <el-col>

                                <el-form-item style="margin-left: 10px" prop="search">
                                    <el-button class="p-button" @click="searchChance" type="primary"
                                               icon="el-icon-search">
                                        Search
                                    </el-button>
                                    <el-button class="button" @click="resetForm" icon="el-icon-refresh">Reset
                                    </el-button>
                                </el-form-item>
                            </el-col>
                        </el-row>
                    </el-form>
                </el-card>


                <el-card class="box-card-result" style="margin-top: 20px;height: 480px;">
                    <div slot="header" class="clearfix">
                        <span class="title">Results</span>
                        <el-button
                            round
                            style="float: right;margin-left: 20px"
                            size="small"
                            type="primary"
                            icon = "el-icon-download"
                            v-show="hasIntersection(chanceAuths.exportButton.show, userRoles)"
                            @click="export2Excel">Export
                        </el-button>
                        <el-button
                            round
                            size="small"
                            type="primary"
                            style="float: right"
                            icon="el-icon-plus"
                            @click="addChanceDialogAppear">New
                        </el-button>
                    </div>

                    <el-table
                        :header-cell-style="{fontSize:'12px',background:'#eef1f6',color:'#495085'}"
                        v-loading="this.$store.getters.isLoading"
                        id="chanceTable"
                        :data="tableData"
                        height="350"
                        fixed
                        row-key="chanceId">
                        <el-table-column
                            prop="chanceId"
                            label="chanceId"
                            sortable
                            width="100">
                        </el-table-column>
                        <el-table-column
                            prop="chanceName"
                            label="chanceName"
                            width="130">
                        </el-table-column>
                        <el-table-column
                            prop="chanceResource"
                            label="chanceResource"
                            width="120">
                        </el-table-column>
                        <el-table-column
                            prop="chancePhase"
                            label="chancePhase"
                            width="160">
                        </el-table-column>
                        <el-table-column
                            prop="chanceTime"
                            label="chanceTime"
                            width="110">
                        </el-table-column>
                        <el-table-column
                            prop="customerMgrDept"
                            label="customerMgrDept"
                            width="110">
                        </el-table-column>
                        <el-table-column
                            prop="customerMgrName"
                            label="customerMgrName"
                            width="120">
                        </el-table-column>
                        <el-table-column
                            prop="chanceStatus"
                            label="chanceStatus"
                            width="150">
                        </el-table-column>
                        <el-table-column
                            label="Operate"

                        >
                            <template slot-scope="scope">
                                <el-button
                                    type="primary" plain round
                                    size="mini"
                                    @click="handleEdit(scope.$index, scope.row)">Edit
                                </el-button>
                                <el-button
                                    type="warning" plain round
                                    size="mini"
                                    @click="handleTrack(scope.$index, scope.row)">Track
                                </el-button>
                            </template>
                        </el-table-column>
                    </el-table>
                    <!--                    <div style="text-align:center">-->
                    <!--                        <el-pagination-->
                    <!--                            @size-change="handleSizeChange"-->
                    <!--                            @current-change="handleCurrentChange"-->
                    <!--                            :current-page="1"-->
                    <!--                            :page-sizes="[100, 200, 300, 400]"-->
                    <!--                            :page-size="100"-->
                    <!--                            layout="total, sizes, prev, pager, next, jumper"-->
                    <!--                            :total="400">-->
                    <!--                        </el-pagination>-->
                    <!--                    </div>-->

                </el-card>

            </el-col>
            <el-col :span="4" style="margin-right: -20px">
                <el-card class="box-card-step">
                    <div slot="header" class="clearfix">
                        <span class="title">Opportunity Stage Description</span>
                        <el-button @click="step=(++step)%7" style="float: right; padding: 3px 0" type="text"> Next
                            Step
                        </el-button>

                    </div>
                    <div style="height: 400px">
                        <el-steps direction="vertical" :active="step">
                            <el-step title="E: Only intention, selection has not started"></el-step>
                            <el-step title="D: Communication displaying"></el-step>
                            <el-step title="C: After the exchange and exhibition, the tender is waiting"></el-step>
                            <el-step title="B: In the bidding"></el-step>
                            <el-step title="A: Bidding, business, contract"></el-step>
                            <el-step title="S: The contract has been signed"></el-step>
                        </el-steps>
                    </div>
                </el-card>

            </el-col>
        </el-row>


    </div>
</template>

<script>
import Bread from "@/components/Bread/Bread";
import AddChanceDialog from "@/views/NPMS/Chance/ChanceManage/Dialog/AddChanceDialog";
import EditChanceDialog from "@/views/NPMS/Chance/ChanceManage/Dialog/EditChanceDialog";
import TrackDialog from "@/views/NPMS/Chance/ChanceManage/Dialog/TrackDialog";
import {options} from "@/data/const";
import {chanceAuths} from "@/data/const";

export default {
    name: "Chance",
    components: {TrackDialog, EditChanceDialog, AddChanceDialog, Bread,},
    props: [],
    data() {
        return {
            userRoles: this.$store.getters.getUser.roles,
            chanceAuths: chanceAuths,
            dialogAddChanceFormVisible: false,
            dialogEditChanceFormVisible: false,
            dialogTrackVisible: false,
            step: 2,
            nextId: 0,
            currentId: 0,

            options: options,

            //查询的表单
            searchChanceForm: {
                "chanceProduct": null,
                "chanceCode": null,
                "chanceName": null,
                "chancePhase": null,
                "chanceBelong": null,
                "chanceStatus": null,
                "chanceType": null,
                "customerMgr": null,
                "customerDept": null,
                "chanceTime": [],
            },

            chanceSearch: {
                "chanceProduct": null,
                "chanceCode": null,
                "chanceName": null,
                "chancePhase": null,
                "chanceBelong": null,
                "chanceStatus": null,
                "chanceType": null,
                "customerMgr": null,
                "customerDept": null,
                "chanceTimeFrom": null,
                "chanceTimeTo": null
            },


            tableData: [{
                chanceId: undefined,
                chanceCode: '001',
                chanceName: 'xxx',
                chanceResource: 'xxx',
                chancePhase: 'xxx',
                chanceTime: '2021-07-19',
                customerMgrDept: 'xxx',
                customerMgrName: 'xxx',

                customerName: "Company",
                chanceBelong: undefined,
                chanceOldCustomer: false,
                chanceBackground: undefined,
            }],
        }
    },

    computed: {},
    watch: {},
    created() {
    },
    mounted() {
        this.loadChance();
        // this.$axios.get("/user/currentUser").then(e => {
        //     console.log(e)
        //     this.userRoles = e.data.data.roles
        //     console.log(this.userRoles)
        //     console.log("aaaaaaa")
        //     console.log(this.tableData)
        // })
    },
    methods: {

        //从后端获取机会数据
        loadChance() {
            let tmp = []
            this.$axios.post(
                '/chance/chance/queryAllChance'
            ).then(e => {
                // console.log("abc"+res.data.obj)
                this.tableData = e.data.obj
                // tmp = e.data.obj
                // let dto = {
                //     "role": this.$store.getters.getUser.roles[0]
                // }
                // console.log(dto)
                // console.log(tmp)
                // this.$axios.post("/approve/approve/searchChanceByUserRole", dto).then(res => {
                //     console.log(res)
                //     for (let i = 0, len = tmp.length; i < len; i++) {
                //         for (let j = 0, length = res.data.obj.length; j < length; j++) {
                //             if (tmp[i].chanceId === res.data.obj[j].chanceId) {
                //                 this.tableData.push(tmp[i])
                //             }
                //         }
                //     }
                //     console.log("this.tableData")
                //     console.log(this.tableData)
                // })
            });

        },

        addChanceDialogAppear() {
            this.dialogAddChanceFormVisible = true;
            // this.$nextTick(() => {
            this.$refs.AddChanceDialogRef.init(this.nextId);
            // })
        },

        searchChance() {
            this.$refs['elForm'].validate(valid => {
                if (!valid) return
                this.chanceSearch.chanceProduct = this.searchChanceForm.chanceProduct
                this.chanceSearch.chanceCode = this.searchChanceForm.chanceCode
                this.chanceSearch.chanceName = this.searchChanceForm.chanceName
                this.chanceSearch.chancePhase = this.searchChanceForm.chancePhase
                this.chanceSearch.chanceBelong = this.searchChanceForm.chanceBelong
                this.chanceSearch.chanceStatus = this.searchChanceForm.chanceStatus
                this.chanceSearch.chanceType = this.searchChanceForm.chanceType
                this.chanceSearch.customerMgr = this.searchChanceForm.customerMgr
                this.chanceSearch.customerDept = this.searchChanceForm.customerDept
                if (this.searchChanceForm.chanceTime.length === 2) {
                    this.chanceSearch.chanceTimeFrom = this.searchChanceForm.chanceTime[0]
                    this.chanceSearch.chanceTimeTo = this.searchChanceForm.chanceTime[1]
                } else {
                    this.chanceSearch.chanceTimeFrom = null
                    this.chanceSearch.chanceTimeTo = null
                }
                console.log(this.chanceSearch)
                this.tableData = []
                let tmp = []
                this.$axios.post("/chance/chance/searchChance", this.chanceSearch).then(e => {
                    console.log(e.data)
                    if (e.data.status === 200) {
                        this.tableData = e.data.obj
                        // tmp = e.data.obj
                        // let dto = {
                        //     "role": this.$store.getters.getUser.roles[0]
                        // }
                        // this.$axios.post("/approve/approve/searchChanceByUserRole", dto).then(res => {
                        //     console.log(res)
                        //     for (let i = 0, len = tmp.length; i < len; i++) {
                        //         for (let j = 0, length = res.data.obj.length; j < length; j++) {
                        //             if (tmp[i].chanceId === res.data.obj[j].chanceId) {
                        //                 this.tableData.push(tmp[i])
                        //             }
                        //         }
                        //     }
                        //     console.log("this.tableData")
                        //     console.log(this.tableData)
                        // })
                    } else {
                        this.tableData = []
                    }
                    this.$message.success("Chance found successfully!")
                })

                // TODO 查询机会
            })
        },
        resetForm() {
            this.$refs['elForm'].resetFields()
        },

        //修改
        handleEdit(index, row) {
            console.log(index, row);
            if (row.chanceStatus === 'Under Process') {
                console.log('Under Process')
                this.$axios.post("/approve/approve/getLatestApprovalByChanceId/" + row.chanceId).then(e => {
                    if(e.data.obj === null || e.data.obj.approvalStatus === 'Returned'){
                        this.dialogEditChanceFormVisible = true;

                        const data = JSON.parse(JSON.stringify(row))
                        console.log(data)

                        this.$nextTick(() => {
                            this.$refs.EditChanceDialogRef.setData(data, index);
                        })
                        // this.currentId=this.tableData[this.tableData.length-1].chanceId
                        this.$refs.EditChanceDialogRef.init();
                    }else{
                        this.$message.error("This chance is not Returned yet, you cannot edit it!")

                    }
                })
            } else if (row.chanceStatus === 'Closed') {
                this.$message.error("This chance has been Closed, you cannot edit it!")
            } else if (row.chanceStatus === 'Paused') {
                this.$message.error("This chance has been Paused, you cannot edit it!")
            } else {
                this.dialogEditChanceFormVisible = true;

                const data = JSON.parse(JSON.stringify(row))
                console.log(data)

                this.$nextTick(() => {
                    this.$refs.EditChanceDialogRef.setData(data, index);
                })
                // this.currentId=this.tableData[this.tableData.length-1].chanceId
                this.$refs.EditChanceDialogRef.init();
            }
        },


        export2Excel: function () {
            let tables = document.getElementById("chanceTable");
            let table_book = this.$XLSX.utils.table_to_book(tables);
            var table_write = this.$XLSX.write(table_book, {
                bookType: "xlsx",
                bookSST: true,
                type: "array"
            });
            try {
                this.$FileSaver.saveAs(
                    new Blob([table_write], {type: "application/octet-stream"}),
                    "chance.xlsx"
                );
            } catch (e) {
                if (typeof console !== "undefined") console.log(e, table_write);
            }
            return table_write;
        },
        //机会跟踪
        handleTrack(index, row) {
            console.log(index, row);
            this.dialogTrackVisible = true;

            this.$nextTick(() => {

                this.$refs.TrackDialogRef.init(row.chanceId);
            })

        },


        //添加机会点击后回调函数
        addChanceCallBack(chance) {

            this.loadChance()
            // this.tableData.push(chance)
            console.log(chance)
        },

        //修改机会点击后回调函数
        editChanceCallBack(chance, index) {
            this.loadChance()
            // console.log("1982734981273984712983479")
            // this.tableData.splice(index,1,chance)
            console.log(chance)
        },

        handleSizeChange(val) {
            console.log(`每页 ${val} 条`);
        },
        handleCurrentChange(val) {
            console.log(`当前页: ${val}`);
        },
        closeAddChance() {
            this.dialogAddChanceFormVisible = false
        },
        closeEditChance() {
            this.dialogEditChanceFormVisible = false
        },
        closeTrackDialog() {
            this.dialogTrackVisible = false
        },
        hasIntersection(arr1, arr2) {
            console.log("arr1")
            console.log(arr1)
            console.log("arr2")
            console.log(arr2)
            return (arr1.length + arr2.length) !== Array.from(new Set([...arr1, ...arr2])).length;
        }
    }
}

</script>

<style scoped>
.text {
    font-size: 14px;
}

.title {
    left: 355px;
    top: 192px;
    width: 72px;
    height: 27px;
    color: rgba(16, 16, 16, 100);
    font-size: 18px;
    text-align: left;
    font-weight: bold;
    font-family: SourceHanSansSC-bold;
}

.clearfix:before,
.clearfix:after {
    display: table;
    content: "";
}

.clearfix:after {
    clear: both
}

.box-card-search {
    height: 250px;

    border-radius: 25px 25px 25px 25px;
}

.box-card-result {
    height: 400px;
    border-radius: 25px 25px 25px 25px;
}

.box-card-step {
    width: 300px;
    height: 600px;
    padding: 20px;
    padding-left: 30px;
    border-radius: 15px;
}
</style>